<template>
  <div class="reg-boxs">
    <div class="breadcrumb-main">
      <div class="breadcrumb-inner">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/web/home' }"
            >首页</el-breadcrumb-item
          >
          <el-breadcrumb-item>供应商注册申请</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    <div class="web-inner-main">
      <span style="color:chocolate"
        >温馨提示：请填写真实有效的信息，审批结果将会以短信形式告知您审核结果，请知晓！</span
      >
      <el-divider></el-divider>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        size="small"
        label-position="center"
        label-width="150px"
        class="demo-ruleForm"
      >
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="登录账号" prop="account">
              <el-input
                v-model="ruleForm.account"
                placeholder="支持字母+数字组合"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登录密码" prop="password" style="position: relative;">
              <el-input
                v-model="ruleForm.password"
                :type="passwordType"
                placeholder="登录密码不少于8位，必须数字+字母+特殊字符组合"
              >
              </el-input>
               <el-button
                  style="position: absolute;right: 0;"
                  @click="pwdSwit"
                  icon="el-icon-view"
                ></el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="name">
              <el-input
                v-model="ruleForm.name"
                placeholder="请填写完整公司名称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="licenseNo">
              <el-input
                v-model="ruleForm.licenseNo"
                placeholder="请输入18位完整信用代码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系人姓名" prop="contactPerson">
              <el-input
                v-model="ruleForm.contactPerson"
                placeholder="请输入真实姓名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input
                v-model="ruleForm.contactPhone"
                placeholder="请输入11位有效手机号码"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="注册邮箱" prop="email">
              <el-input
                v-model="ruleForm.email"
                placeholder="请输入有效邮箱格式"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验证码" prop="code">
              <el-input v-model="ruleForm.code" placeholder="请输入验证码">
                <el-button
                  slot="append"
                  type="primary"
                  @click="smsSend"
                  size="mini"
                  >{{ state.sendTimeText }}</el-button
                >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="实际办公地址" prop="businessAddresss">
              <el-input
                v-model="ruleForm.businessAddresss"
                placeholder="请输入实际办公地址"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="公司简介" prop="descr">
              <el-input
                v-model="ruleForm.descr"
                placeholder="请介绍公司主营业务"
                maxlength="300"
                show-word-limit
                type="textarea"
                :rows="4"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传营业执照" prop="licenseFile">
              <el-upload
                class="avatar-uploader"
                v-model="ruleForm.licenseFile"
                accept="image/*,application/pdf"
                list-type="picture"
                :on-preview="handlePreview"
                :file-list="fileList"
                :before-upload="beforeAvatarUpload"
                action="#"
                :http-request="onChangeFile"
              >
                  <el-button type="primary" size="mini">上传</el-button>
                  <div slot="tip" style="display: inline-block;margin-left: 20px;" class="el-upload__tip">支持图片和pdf</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- <form-create 
            v-model="fApi" 
            :rule="rule" 
            :option="option"
            @btn-img-click="uplaodImg"/> -->
      <!-- <input
        type="file"
        ref="pdfFile"
        @change="pdfChange"
        style="display: none;"
      /> -->
    </div>
    <div style="padding:24px;text-align: center;">
      <el-button type="danger" size="medium" @click="regForm('ruleForm')"
        >重置</el-button
      >
      <el-button type="primary" size="medium" :loading="loading" @click="taskSubmit('ruleForm')"
        >提交审核</el-button
      >
    </div>

    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img :src="previewUrl" alt="图片预览" class="previcew-img">
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog title="协议申明" :visible.sync="regVisible" :close-on-click-modal="false" :show-close="false">
      <div v-html="regInfo" class="senp ql-editor ql-snow"></div>
      <template #footer>
        <div class="dialog-footer">
          <div class="filex">
             <el-checkbox v-model="regChecked">
              <span class="cols">我已认真阅读并理解以上条款内容，对此表示完全认同并承诺严格遵照执行。</span>
             </el-checkbox>
          </div>
          <el-button type="primary" :disabled="!regChecked" @click="regVisible = false">下一步</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import { supplierRegApply, getPhoneCode,supplierPageFind } from "@/api/supplier_api";
import { getWebSupplierInfo } from "@/api/about_api";
import {
  validateAccount,
  checkPwd,
  checkEmail,
  checkPhone,
  CheckSocialCreditCode,
  loginMD5
} from "@/utils/index";
import pdfimg from "@/assets/pdf_file.png";
export default {
  name: "webReg",
  data() {
    var valiAccount = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入账号"));
      }
      let size = validateAccount(value);
      if (size == 1) {
        callback(new Error("不能有空格"));
      } else if (size == 2) {
        callback(new Error("不能有特殊字符"));
      } else if (size == 3) {
        callback(new Error("只支持数字+字母组合"));
      }
      callback();
    };
    var valiPwd = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入登录密码"));
      }
      let size = checkPwd(value);
        if (!size) {
          callback(new Error("登录密码不少于8位，必须数字+字母+特殊字符组合"));
        }
        callback();

      // let size = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/.test(value);
      // if (!size) {
      //   callback(new Error("密码不少于6位，必须数字+字母组合"));
      // }
      callback();
    };
    var valiLicense = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入统一社会信用代码"));
      }
      let size = CheckSocialCreditCode(value);
      if (!size) {
        callback(new Error("统一社会信用代码输入格式有误"));
      }
      callback();
    };
    var valiPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入联系电话"));
      }
      let size = checkPhone(value);
      if (!size) {
        callback(new Error("联系电话输入格式有误"));
      }
      callback();
    };
    var valiEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入注册邮箱"));
      }
      let size = checkEmail(value);
      if (!size) {
        callback(new Error("注册邮箱输入格式有误"));
      }
      callback();
    };
     var validName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入公司名称"));
      }
      callback();
    };
    return {
      passwordType: "password",
      ruleForm: {
        account: "",
        password: "",
        name: "",
        licenseNo: "",
        contactPerson: "",
        contactPhone: "",
        email: "",
        code: "",
        businessAddresss: "",
        descr:'',
        licenseFile: ""
      },
      loading: false,
      rules: {
        account: [{ required: true, validator: valiAccount, trigger: "blur" }],
        password: [{ required: true, validator: valiPwd, trigger: "blur" }],
        name: [{ required: true, validator:validName, trigger: "blur" }],
        licenseNo: [
          { required: true, validator: valiLicense, trigger: "blur" }
        ],
        contactPerson: [
          { required: true, message: "请输入联系人姓名", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, validator: valiPhone, trigger: "change" }
        ],
        email: [{ required: true, validator: valiEmail, trigger: "blur" }],
        code: [
          { required: true, message: "请输入手机验证码", trigger: "blur" }
        ],
        businessAddresss: [
          { required: true, message: "请输入实际办公地址", trigger: "blur" }
        ],
        descr: [
          { required: true, message: "请输入公司简介", trigger: "blur" }
        ],
        licenseFile: [
          { required: true, message: "请上传营业执照", trigger: "blur" }
        ]
      },
      state: {
        sendTimeText: "获取验证码",
        isSendState: false,
        timeCounter: null,
        countdown: 60
      },
      hisPwd:'',
      fileList: [],
      // 预览对话框是否显示
      dialogVisible: false,
      // 预览图片的 URL
      previewUrl: '',
      regVisible: false,
      regChecked: false,
      regInfo: '',
      tableData:[]
    };
  },
  computed: {
    ...mapGetters(["smsType","uploadType","findType"])
  },
  mounted() {
    this.getCustom()
   // this.loadList()
  },
  methods: {
    ...mapActions({
      uploadFile: "user/regUploadFile"
    }),
    async loadList() {
       let param = {};
      param.statusFlag = "0"
      param.pageNum = 1;
      param.pageSize = 500
      param.queryType = this.findType["reg"];
      const { code, data } = await supplierPageFind(param);
      if (code == 200) {
        this.tableData = data?.list ?? []
      }
    },
    async getCustom() {
      this.regInfo = ""
      const { code, data } = await getWebSupplierInfo("supplierInfo");
      if (code === 200) {
        this.regInfo = data
        if (data) {
          this.regVisible = true
        }
      }
    },
    regForm(formName) {
      this.$refs[formName].resetFields();
      this.fileList = [];
      this.clartTime();
    },
    handlePreview(file) {
      if (file.type == 1) {
        window.open(file.urls)
      } else {
        this.previewUrl = file.url;
        this.dialogVisible = true;
      }
      },
    async onChangeFile(file, fileList) {
      const url = await this.uploadFile({ fileKey:'regImg',data: file });
      if (url) {
        if (file.file.type == 'application/pdf') {
          this.fileList.push({name:file.file.name,url:pdfimg,urls:url,type:1})
        } else {
          this.fileList.push({name:file.file.name,url:url,type:2})
        }
        this.ruleForm.licenseFile = url;
      }
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg" ||
        file.type === "application/pdf";
        const isLt200M = file.size / 1024 / 1024 < 200;

      if (!isJPG) {
        this.$message.error("营业执照只能是 jpeg，png，jpg 格式或pdf格式!");
      }
      if (!isLt200M) {
        this.$message.error("附件大小不能超过 200MB!");
      }
       return isJPG && isLt200M;
    },
    async smsSend() {
      if (this.state.isSendState) {
        this.$message.error("不能重复发送");
        return;
      }
      if (!this.ruleForm.contactPhone) {
        this.$message.error("请输入联系电话");
        return;
      }
      let size = checkPhone(this.ruleForm.contactPhone);
      if (!size) {
        this.$message.error("联系电话输入格式有误");
        return;
      }
      let param = {};
      param.phone = this.ruleForm.contactPhone;
      param.type = this.smsType["reg"];
      const { code } = await getPhoneCode(param);
      if (code == 200) {
        this.state.isSendState = true;
        this.settime();
      }
    },
    settime() {
      let that = this;
      if (this.state.countdown == 0) {
        this.clartTime();
        return false;
      } else {
        this.state.sendTimeText = "倒计时(" + this.state.countdown + ")s";
        this.state.countdown--;
      }
      this.state.timeCounter = setTimeout(function() {
        that.settime();
      }, 1000);
    },
   async taskSubmit(formName) {
    let that = this
      this.$refs[formName].validate(async valid => {
        if (valid) {
          let urls = []
          this.fileList.forEach(v => {
            if (v.type == 1) {
              urls.push(v.urls)
            } else {
              urls.push(v.url)
            }
          })
          const postData = {...this.ruleForm}
         // this.ruleForm.licenseFile = urls.join(',')
          const pws = postData.password + process.env.VUE_APP_FILE_Name
          postData.password = loginMD5(pws)
           postData.licenseFile = urls.join(',')
          this.loading = true
          try { 
           const req = await supplierRegApply(postData);
            if (req.code === 200) {
              this.$confirm('申请成功，等待管理员审核，结果会通过短信发送到手机，敬请留意。请牢记登录账号和密码，通过审核后登录系统唯一凭证。', '温馨提示', {
                confirmButtonText: '关闭',
                cancelButtonText: '取消',
                showCancelButton: false,
                closeOnClickModal:false,
                type: 'success'
              }).then(() => {
                that.regForm("ruleForm");
              }).catch(() => {});
            } else {
              this.clartTime();
            }
          } finally {
            this.loading = false;
          }
        } else {
          return false;
        }
      });
    },
    clartTime() {
      clearTimeout(this.state.timeCounter);
      this.state.isSendState = false;
      this.state.sendTimeText = "获取验证码";
      this.state.countdown = 60;
    },
    pwdSwit() {
      if (!this.ruleForm.password) return;
      if (this.passwordType == "password") {
        this.passwordType = "text";
      } else {
        this.passwordType = "password";
      }
    }
  },
   destroyed(){
    this.clartTime()
 }
};
</script>
<style scoped>
.dialog-footer{
  display: flex;
  align-items: center;
}
.filex{
  color: #409eff;
  flex: 1;
  text-align: left;
}
.cols{
  color: #409eff;
}
.senp{
  padding: 20px;
}
.reg-boxs{
}
</style>
